package com.idemon.ds.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;

import com.idemon.config.Consts;
import com.idemon.ds.model.Category;
import com.jfinal.kit.PropKit;
import com.jfinal.render.FreeMarkerRender;

import freemarker.template.TemplateModelException;

/**
 * Servlet Filter implementation class InitDataFilter
 */
public class InitDataFilter implements Filter {
	private Logger log = Logger.getLogger(getClass());

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		Object obj = request.getServletContext().getAttribute(Consts.ATTR_KEY_CATEGORY_LIST);
		Long categoryTimestamp = (Long) request.getServletContext()
				.getAttribute(Consts.ATTR_KEY_CATEGORY_LIST_TIMESTAMP);
		Long currTime = System.currentTimeMillis();
		// 如果对象不存在或者已经超过一天，那么重新获取数据，并更新时间
		if ((obj == null) || (categoryTimestamp == null) || (currTime - categoryTimestamp > PropKit
				.getLong(Consts.ATTR_KEY_INIT_DATA_OUTTIME, Consts.DEFAULT_INIT_DATA_OUTTIME))) {
			obj = Category.dao.getAll();
			request.getServletContext().setAttribute(Consts.ATTR_KEY_CATEGORY_LIST, obj);
			request.getServletContext().setAttribute(Consts.ATTR_KEY_CATEGORY_LIST_TIMESTAMP, currTime);
			try {
				FreeMarkerRender.getConfiguration().setSharedVariable(Consts.ATTR_KEY_CATEGORY_LIST, obj);
			} catch (TemplateModelException e) {
				log.error("初始化类别数据失败", e);
			}
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {

	}

}
